<template>
    <div v-loading="loading" class="role-box">
        <el-container class="common" style="border: 1px solid #eee;height: 100%">
            <el-aside width="50%" class="role">
                <el-header class=" common" style="line-height:40px;--el-header-height:40px">
                    <el-button type="success" @click="addRole" class="button"><el-icon>
                            <CirclePlus />
                        </el-icon>{{$t('webAuto.newlyAdded')}}</el-button>
                    <el-button type="primary" @click="editRole" class="button"><el-icon>
                            <Edit />
                        </el-icon>{{$t('webAuto.edit')}}</el-button>
                    <el-button type="danger" @click="deleteRole" class="button"><el-icon>
                            <Close />
                        </el-icon>{{$t('webAuto.delete')}}</el-button>
                </el-header>
                <el-main class="common" style="display: flex;flex-direction: column;">
                    <el-table :data="data.tableRole" style="width: 100%;height: 95%;" border
                        :header-cell-style="{ color: '#000', fontWeight: 'bold' }" highlight-current-row
                        @current-change="highlightCurrentChange" :cell-style="{ whiteSpace: 'pre-wrap' }"
                        @row-dblclick="rowClick">
                        <el-table-column :label="$t('module.serialNo')" width="70" align="center">
                            <template #default="scope">{{ (data.currentPage - 1) * data.pageSize + scope.$index + 1
                                }}</template>
                        </el-table-column>
                        <el-table-column type="selection" width="50" align="center">
                            <template #default="scope">
                                <el-checkbox v-model="scope.row.selected" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="roleName" :label="$t('webAuto.jiaoseMingcheng')" />
                        <el-table-column prop="roleId" label="Code" width="280" />
                        <el-table-column prop="created" :label="$t('webAuto.chuangjianTime')" width="170" />
                    </el-table>
                    <div class="demo-pagination-block">
                        <el-pagination :currentPage="data.currentPage" :page-size="data.pageSize"
                            :page-sizes="[15, 30, 50]" :small="small" :disabled="disabled" :background="background"
                            layout="total, sizes, prev, pager, next, jumper" :total="data.total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </el-main>
            </el-aside>
            <el-main class="people">
                <!-- 人员角色 -->
                <div class="people-main">
                    <el-header class="role-heaer common">
                        <el-row>
                            <div class="flex">
                                <span style="margin-right: 10px;">{{$t('webAuto.workNumber')}}/{{$t('webAuto.fullName')}}:</span>
                                <el-input v-model="data.userName" style="width: 320px"
                                    :placeholder="$t('webAuto.xianJiaoseZaixinm')" />
                            </div>
                            <div style="margin-left: 10px;">
                                <el-button plain @click="peopleSelect" class="button"><el-icon>
                                        <Search />
                                    </el-icon>{{$t('webAuto.query')}}</el-button>
                                <el-button type="info" class="button" plain
                                    @click="data.userName = ''; peopleDetail()"><el-icon>
                                        <RefreshLeft />
                                    </el-icon>{{$t('calendar.rest')}}</el-button>
                                <el-button type="success" @click="pickerClick" class="button"><el-icon>
                                        <Plus />
                                    </el-icon>{{$t('webAuto.AddChenyuan')}}</el-button>
                                <el-button type="danger" @click="deletePeopleClick" class="button"><el-icon>
                                        <SemiSelect />
                                    </el-icon>{{$t('webAuto.DelChenyuan')}}</el-button>
                            </div>
                        </el-row>
                    </el-header>
                    <el-main class="common" style="flex:1;display:flex;flex-direction:column;">
                        <el-table :data="data.tablePeople" style="width: 100%;height: 95%;" border
                            :header-cell-style="{ color: '#000', fontWeight: 'bold' }" highlight-current-row
                            @selection-change="handleSelectionChange" :cell-style="{ whiteSpace: 'pre-wrap' }"
                            @row-dblclick="rowClick">
                            <el-table-column :label="$t('module.serialNo')" width="70" align="center">
                                <template #default="scope">{{ (data.currentPage2 - 1) * data.pageSize2 + scope.$index +
        1
                                    }}</template>
                            </el-table-column>
                            <el-table-column type="selection" width="50" align="center" />
                            <el-table-column prop="userId" :label="$t('webAuto.yuanggongNum')" />
                            <el-table-column prop="userName" :label="$t('webAuto.fullName')" />
                            <el-table-column prop="deptName" :label="$t('webAuto.department')" />
                        </el-table>
                        <div class="demo-pagination-block">
                            <el-pagination :currentPage="data.currentPage2" :page-size="data.pageSize2"
                                :page-sizes="[15, 30, 50]" :small="small" :disabled="disabled" :background="background"
                                layout="total, sizes, prev, pager, next, jumper" :total="data.total2"
                                @size-change="handleSizeChange2" @current-change="handleCurrentChange2" />
                        </div>
                    </el-main>
                </div>
                <!-- 菜单角色 -->
                <div class="menu-main">
                    <el-header class="role-heaer common">
                        <el-row>
                            <div style="margin-left: 10px;">
                                <el-button type="success" @click="menuClick" class="button"><el-icon>
                                        <Plus />
                                    </el-icon>{{$t('webAuto.newlyAdded')}}</el-button>
                                <el-button type="danger" @click="deleteMenuClick" class="button"><el-icon>
                                        <SemiSelect />
                                    </el-icon>{{$t('webAuto.delete')}}</el-button>
                            </div>
                        </el-row>
                    </el-header>
                    <el-main class="common" style="flex:1;display:flex;flex-direction:column;">
                        <el-table :data="data.tableMenu" style="width: 100%;height: 95%;" border
                            :header-cell-style="{ color: '#000', fontWeight: 'bold' }" highlight-current-row
                            @selection-change="handleSelectionChange2" :cell-style="{ whiteSpace: 'pre-wrap' }"
                            @row-dblclick="rowClick">
                            <el-table-column :label="$t('module.serialNo')" width="70" align="center">
                                <template #default="scope">{{ (data.currentPage2 - 1) * data.pageSize2 + scope.$index +
        1
                                    }}</template>
                            </el-table-column>
                            <el-table-column type="selection" width="50" align="center" />
                            <el-table-column prop="menusName" :label="$t('webAuto.manuName')" />
                        </el-table>
                        <div class="demo-pagination-block">
                            <el-pagination :currentPage="data.currentPage3" :page-size="data.pageSize3"
                                :page-sizes="[15, 30, 50]" :small="small" :disabled="disabled" :background="background"
                                layout="total, sizes, prev, pager, next, jumper" :total="data.total3"
                                @size-change="handleSizeChange3" @current-change="handleCurrentChange3" />
                        </div>
                    </el-main>
                </div>
            </el-main>
        </el-container>
        <!-- 角色的弹框 -->
        <el-dialog v-if="data.dialogRoleVisible" v-model="data.dialogRoleVisible" :title="data.isshow ? $t('webAuto.AddJiaoSe') : $t('webAuto.EditJiaoSe')"
            width="500" destroy-on-close :close-on-click-modal="false">
            <el-form :model="form" ref="ruleFormRef" :rules="rules">
                <el-form-item :label="$t('webAuto.name')" :label-width="100" prop="roleName">
                    <el-input v-model="form.roleName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="Code" :label-width="100" prop="roleId">
                    <el-input v-model="form.roleId" autocomplete="off" :readonly="!data.isshow" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.dialogRoleVisible = false">{{$t('webAuto.cancel')}}</el-button>
                    <el-button type="primary" v-if="data.isshow" @click="saveClick">
                        {{$t('webAuto.bangcun')}}
                    </el-button>
                    <el-button type="primary" @click="updateClick" v-else>
                        {{$t('webAuto.gengxing')}}
                    </el-button>
                </div>
            </template>
        </el-dialog>
          <!-- 菜单的弹框 -->
          <el-dialog v-if="data.dialogMenuVisible" v-model="data.dialogMenuVisible" :title="$t('webAuto.AddJiaoSe')"
            width="500" destroy-on-close :close-on-click-modal="false">
            <el-form :model="forms" ref="ruleFormRef" :rules="rules">
                <el-form-item :label="$t('webAuto.manuName')" :label-width="100" prop="menusName">
                    <el-input v-model="forms.menusName" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.dialogMenuVisible = false">{{$t('webAuto.cancel')}}</el-button>
                    <el-button type="primary"  @click="saveMenusClick">
                        {{$t('webAuto.bangcun')}}
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <org-picker ref="orgPicker" :position="'center'" :multiple="true" type="user" :selected="_value"
            @ok="savePeopleClick"></org-picker>
    </div>
</template>

<script setup>
import roleApi from '@/api/role'
import { onMounted, reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import OrgPicker from '../../../components/common/OrgPicker.vue'
import { useI18n } from 'vue-i18n';


const { t } = useI18n();

// 表格绑定的样式
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let loading = ref('false')
const data = reactive({
    tableRole: [],
    pageSize: 15,
    currentPage: 1,
    total: 0,
    selectedRow: null,
    liRow: {},//选择的当前行
    roleId: '', //角色id
    roleName: '',//角色名称
    userName: '',//用户名称
    dialogRoleVisible: false,
    isshow: false,
    menusShow: false,
    dialogMenuVisible: false,
    tablePeople: [],
    currentPage2: 1,
    pageSize2: 15,
    total2: 0,
    peopleShow: false,
    liPeopleRow: [],
    tableMenu:[],
    currentPage3: 1,
    pageSize3: 15,
    total3: 0,
    liMenusRow:[]
})

const form = reactive({
    roleName: '',
    roleId: ''
})

const forms=reactive({
    menusName:''
})

const ruleFormRef = ref(null)
const rules = reactive({
    roleName: [{ required: true, message: t('webAuto.entName'), trigger: 'blur' }],
    roleId: [{ required: true, message: t('webAuto.entCode'), trigger: 'blur' }],
    menusName: [{ required: true, message: t('webAuto.entManuName'), trigger: 'blur' }],
})
//表单验证
const validator = async (callback) => {
    try {
        return await ruleFormRef.value.validate()
    }
    catch (error) {
        return false
    }

}

onMounted(() => {
    roleDetail()
})

// 获取角色信息
const roleDetail = () => {
    loading.value = true
    roleApi.getRoleDetail({
        pageSize: data.pageSize,
        pageNo: data.currentPage,
        roleId: data.roleId,
        roleName: data.roleName
    }).then(res => {
        loading.value = false
        data.tableRole = res.data.records
        data.total = res.data.total
        data.tableRole.forEach(item => {
            item.selected = false
        })
    }).catch((e) => {
        loading.value = false
    })
}

// 表格分页
const handleSizeChange = val => {
    data.pageSize = val
    roleDetail()
}
const handleCurrentChange = val => {
    data.currentPage = val
    roleDetail()
}
// 角色表格单击或者双击
const rowClick = (e) => {
    console.log(e)
}

const highlightCurrentChange = (rows) => {
    data.liRow = rows
    data.tableRole.forEach((item, index) => {
        if (item.roleId == rows.roleId) {
            item.selected = true
        } else {
            item.selected = false
        }
    })

    data.roleId = data.liRow.roleId
    data.roleName = data.liRow.roleName
    peopleDetail()
    menus()
}

// 新增角色表格
const addRole = () => {
    data.dialogRoleVisible = true
    data.isshow = true
}
// 保存
const saveClick = () => {
    let validate = validator().then(result => {
        console.log(result); // 成功：打印 '操作成功！'
    }).catch(error => {
        console.error(error); // 失败：打印 '操作失败！'
    })
    // console.log(validate)
    if (!validate) {
        ElMessage.error(t('webAuto.BiaoDanError'))
        return
    }
    roleApi.getRoleadd(form).then(res => {
        ElMessage.success(t('webAuto.baocunChenGong'))
        data.dialogRoleVisible = false
        window.location.reload()
        roleDetail()
    }).catch(err => {
        console.log(err)
        ElMessage.error(t('webAuto.roleDefinitions'))
        data.dialogRoleVisible = true
    })
}

// 编辑角色表格
const editRole = () => {
    data.isshow = false
    if (!('roleId' in data.liRow)) {
        ElMessage.error(t('webAuto.selectRowEdit'))
    } else {
        data.dialogRoleVisible = true
        form.roleId = data.liRow.roleId
        form.roleName = data.liRow.roleName
    }
}
const updateClick = () => {
    roleApi.getRoleUpdate(form).then(res => {
        ElMessage.success(t('webAuto.gengxingChenGong'))
        data.dialogRoleVisible = false
        window.location.reload()
        roleDetail()
    }).catch(err => {
        ElMessage.error(t('webAuto.gengxingShiBai'))
        window.location.reload()
        data.dialogRoleVisible = true
    })
}
const deleteRole = () => {
    if (!('roleId' in data.liRow)) {
        ElMessage.error(t('webAuto.selectRowDel'))
    } else {
        ElMessageBox.alert(t('webAuto.confirmRoleNeedDeleted'), t('webAuto.roleDeleted'), {
            confirmButtonText: t('webAuto.sure'),
            callback: action => {
                if (action === 'confirm') {
                    // 在用户确认后发送自定义接口请求
                    roleApi.getRoleDelete(data.liRow.roleId).then(res => {
                        ElMessage.success(t('webAuto.DeleteSuccessfully'))
                        window.location.reload()
                    }).catch(err => {
                        ElMessage.error(t('webAuto.DeleteFailed'))
                    })
                }
            }
        })
    }
}

// 人员列表
const peopleDetail = () => {
    roleApi.getPeopleDetail({
        pageSize: data.pageSize2,
        pageNo: data.currentPage2,
        roleId: data.roleId,
        userName: data.userName
    }).then(res => {
        data.tablePeople = res.data.records
        data.total2 = res.data.total
    }).catch(err => {
        ElMessage.error(t('webAuto.NoDataAvailable'))
    })
}
// 表格分页
const handleSizeChange2 = val => {
    data.pageSize2 = val
    peopleDetail()
}
const handleCurrentChange2 = val => {
    data.currentPage2 = val
    peopleDetail()
}

// 添加人员信息
const orgPicker = ref()
const _value = ref([])
const pickerClick = () => {
    if (data.roleId.length == 0) {
        ElMessage.error(t('webAuto.qingxianJSzaiRY'))
    } else {
        orgPicker.value.show()
    }
}
// 保存
const savePeopleClick = (val) => {
    _value.value = val
    let userIds = []
    val.forEach(item => {
        userIds.push(item.id)
    })
    roleApi.getPeopleAdd({
        roleId: data.roleId,
        userIds
    }).then(res => {
        ElMessage.success(t('webAuto.AddSuccessfully'))
        window.location.reload()
    }).catch(err => {
        ElMessage.error(t('webAuto.AddFailed'))
    })
}

const handleSelectionChange = (rows) => {
    data.liPeopleRow = rows
}
// 移除 成员
const deletePeopleClick = () => {
    if (data.liPeopleRow.length == 0) {
        ElMessage.error(t('webAuto.selectMembersRemoved'))
    } else {
        let ids = []
        data.liPeopleRow.forEach(item => {
            console.log(item)
            ids.push(item.id)
        })
        ElMessageBox.alert(t('webAuto.confirmMembersRemoved'), t('webAuto.RemovMember'), {
            confirmButtonText: t('webAuto.sure'),
            callback: action => {
                if (action === 'confirm') {
                    // 在用户确认后发送自定义接口请求
                    roleApi.getPeopleDelete({ ids }).then(res => {
                        console.log(res)
                        ElMessage.success(t('webAuto.RemovSuccessfully'))
                        window.location.reload()
                    }).catch(err => {
                        console.log(err)
                        ElMessage.error(err.message)
                    })
                }
            }
        })
    }
}

// 人员查询
const peopleSelect = () => {
    if (data.roleId.length == 0) {
        ElMessage.error(t('webAuto.selectRoleFirstAndEnterTheQuery'))
    } else if (data.userName.length == 0) {
        ElMessage.error(t('webAuto.enterTheQuery'))
    } else {
        peopleDetail()
    }
}

// 菜单角色
const menus=()=>{
    roleApi.getMenuseDetail({
        roleId: data.roleId,
        pageSize:data.pageSize3,
        pageNo:data.currentPage3
    }).then(res => {
        data.tableMenu = res.data.records
        data.total3 = res.data.total
    }).catch(err => {
        ElMessage.error(t('webAuto.NoDataAvailable'))
    })
}

// 表格分页
const handleSizeChange3 = val => {
    data.pageSize2 = val
    menus()
}
const handleCurrentChange3 = val => {
    data.currentPage2 = val
    menus()
}

// 添加和删除
const menuClick=()=>{
    if (data.roleId.length == 0) {
        ElMessage.error(t('webAuto.selectRoleFirstThenAddMenuPermission'))
        return
    }
    data.menusShow=true
    data.dialogMenuVisible=true

}
const saveMenusClick=()=>{
    roleApi.getMenusAdd({
        roleId: data.roleId,
        menusName:forms.menusName
    }).then(res => {
        ElMessage.success(res)
        window.location.reload()
    }).catch(err => {
        ElMessage.error(err.message)
    })
}
const handleSelectionChange2 = (rows) => {
    data.liMenusRow = rows
}
const deleteMenuClick=()=>{
    if (data.liMenusRow.length == 0) {
        ElMessage.error(t('webAuto.selectDelMenuPermission'))
    }else{
        let ids = []
        data.liMenusRow.forEach(item => {
            ids.push(item.id)
        })
        ElMessageBox.alert(t('webAuto.confirmDelMenuPermission'), t('webAuto.MenuPermission'), {
            confirmButtonText: t('webAuto.sure'),
            callback: action => {
                if (action === 'confirm') {
                    // 在用户确认后发送自定义接口请求
                    roleApi.getMenusDelete(ids).then(res => {
                        ElMessage.success(res)
                        window.location.reload()
                    }).catch(err => {
                        ElMessage.error(err.message)
                    })
                }
            }
        })
    }
}
</script>

<style scoped lang="less">
.role-box {
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    overflow: hidden;
}

.common {
    margin: 0 !important;
    padding: 0 !important;
}

.role {
    margin: 0 !important;
    padding: 5px !important;
    border-right: 1px solid #cecece;
    display: flex;
    flex-direction: column;
}

.role-heaer {
    line-height: 40px !important;
    --el-header-height: 40px !important;
}

.demo-pagination-block {
    height: 40px;
    margin: 5px 0px;
    padding: 0 2px;
    box-sizing: border-box;
    font-size: 12px;
    background-color: #faf8f8;
}

.people {
    height: 100%;
    margin: 0 !important;
    padding: 5px !important;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .people-main {
        height: 50%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .menu-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
}

// 按钮样式
.button {
    padding: 5px 10px;
    font-size: 12px;
    height: 25px;
}
</style>